package com.sky.task;


import cn.hutool.core.collection.CollUtil;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
//@Component
public class OrderTask {
    private final OrderMapper orderMapper;

    /**
     * 处理支付超时订单
     */
    @Scheduled(cron = "*/5 * * * * ?")
    public void processOverPayTime() {
        log.info("处理支付超时订单：{}", LocalDateTime.now());
        //一.处理超时15分钟还没有支付的订单
        //1.1获取当前时间-15分钟
        LocalDateTime overPayTime = LocalDateTime.now().minusMinutes(15);
        //查表
        List<Orders> ordersList = orderMapper.selectByStatusAndORderTime(Orders.PENDING_PAYMENT, overPayTime);
        //处理超时订单
        if (CollUtil.isNotEmpty(ordersList)) {
            ordersList.forEach(orders -> {
                orders.setStatus(6);
                orders.setCancelReason("支付超时,订单已取消");
                orders.setCancelTime(LocalDateTime.now());
            });
            orderMapper.updateById(ordersList);

        }

    }
    /**
     * 处理“派送中”状态的订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processDeliveryOrder(){
        log.info("处理派送中订单：{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().minusHours(1);
        List<Orders> ordersList =
                orderMapper.selectByStatusAndORderTime(Orders.DELIVERY_IN_PROGRESS, time);
        if(CollUtil.isNotEmpty(ordersList)){
            ordersList.forEach(order -> {
                order.setStatus(Orders.COMPLETED);
            });
            orderMapper.updateById(ordersList);
        }
    }
}
